<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="站点名称" prop="stationName">
        <el-input
          v-model="queryParams.stationName"
          placeholder="请输入站点名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="语音类型" prop="announcementType">
        <el-select v-model="queryParams.announcementType" placeholder="请选择语音类型" clearable>
          <el-option label="即将到站" value="next"></el-option>
          <el-option label="已到达" value="arrival"></el-option>
          <el-option label="发车" value="departure"></el-option>
          <el-option label="换乘提示" value="transfer"></el-option>
          <el-option label="终点站" value="terminal"></el-option>
          <el-option label="安全提示" value="safety"></el-option>
          <el-option label="自定义" value="custom"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入语音文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="播放速度" prop="voiceSpeed">
        <el-select v-model="queryParams.voiceSpeed" placeholder="请选择播放速度" clearable>
          <el-option label="慢速" value="slow"></el-option>
          <el-option label="正常" value="normal"></el-option>
          <el-option label="快速" value="fast"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件状态" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择文件状态" clearable>
          <el-option label="正常" :value="1"></el-option>
          <el-option label="已删除" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bus:files:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bus:files:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-pie-chart"
          size="mini"
          @click="showStatistics"
        >统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="filesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="站点名称" align="center" prop="stationName" width="150" />
      <el-table-column label="语音类型" align="center" prop="announcementType" width="100">
        <template slot-scope="scope">
          <el-tag :type="getVoiceTypeTagType(scope.row.announcementType)">
            {{ getVoiceTypeLabel(scope.row.announcementType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="语音文件名" align="center" prop="fileName" width="180" />
      <el-table-column label="文件大小" align="center" prop="fileSize" width="100">
        <template slot-scope="scope">
          <span>{{ formatFileSize(scope.row.fileSize) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="播放速度" align="center" prop="voiceSpeed" width="80" />
      <el-table-column label="语音语调" align="center" prop="voiceTone" width="80" />
      <el-table-column label="文件状态" align="center" prop="isActive" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isActive === 1 ? 'success' : 'danger'">
            {{ scope.row.isActive === 1 ? '正常' : '已删除' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="140">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="playStationAudio(scope.row)"
            v-if="scope.row.isActive === 1"
          >播放</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bus:files:remove']"
            style="color: #f56c6c;"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 语音文件详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <div style="margin-bottom: 15px;">
        <h4 style="margin: 0; color: #409EFF; font-size: 16px;">
          {{ form.stationName }} -
          <el-tag :type="getVoiceTypeTagType(form.announcementType)" style="margin-left: 5px;">
            {{ getVoiceTypeLabel(form.announcementType) }}
          </el-tag>
        </h4>
      </div>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="站点名称">{{ form.stationName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="语音类型">
          <el-tag :type="getVoiceTypeTagType(form.announcementType)">
            {{ getVoiceTypeLabel(form.announcementType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="语音文件名">{{ form.fileName }}</el-descriptions-item>
        <el-descriptions-item label="文件大小">{{ formatFileSize(form.fileSize) }}</el-descriptions-item>
        <el-descriptions-item label="语音时长">{{ form.duration ? form.duration + 's' : '-' }}</el-descriptions-item>
        <el-descriptions-item label="播放速度">{{ form.voiceSpeed || '-' }}</el-descriptions-item>
        <el-descriptions-item label="语音语调">{{ form.voiceTone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="TTS版本">{{ form.ttsModelVersion || '-' }}</el-descriptions-item>
        <el-descriptions-item label="文件状态">
          <el-tag :type="form.isActive === 1 ? 'success' : 'danger'">
            {{ form.isActive === 1 ? '正常' : '已删除' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(form.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="文件路径" :span="2">
          <el-input v-model="form.filePath" readonly />
        </el-descriptions-item>
      </el-descriptions>

      <div style="margin-top: 20px;" v-if="form.filePath && form.isActive === 1">
        <el-divider content-position="left">语音播放</el-divider>
        <div style="text-align: center; margin-bottom: 10px;">
          <el-button type="primary" icon="el-icon-video-play" @click="playStationAudio(form)">
            播放 {{ form.stationName }} - {{ getVoiceTypeLabel(form.announcementType) }}
          </el-button>
        </div>
        <audio :src="form.filePath" controls style="width: 100%;">
          您的浏览器不支持音频播放
        </audio>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFiles, getFiles, delFiles, addFiles, updateFiles } from "@/api/bus/files"

export default {
  name: "Files",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 语音文件管理，存储TTS合成的各站点、各语言、各类型的报站语音文件表格数据
      filesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationName: null,
        announcementType: null,
        fileName: null,
        voiceSpeed: null,
        voiceTone: null,
        isActive: null,
        createdAt: null
      },
      // 表单参数
      form: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询语音文件管理，存储TTS合成的各站点、各语言、各类型的报站语音文件列表 */
    getList() {
      this.loading = true
      listFiles(this.queryParams).then(response => {
        this.filesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看详情 */
    handleView(row) {
      this.form = { ...row }
      this.open = true
      this.title = "语音文件详情"
    },
    /** 播放站点语音 */
    playStationAudio(row) {
      if (!row.filePath) {
        this.$message.error('文件路径不存在')
        return
      }

      // 显示播放提示
      const voiceTypeLabel = this.getVoiceTypeLabel(row.announcementType)
      this.$message.info(`正在播放：${row.stationName} - ${voiceTypeLabel}`)

      const audio = new Audio(row.filePath)
      audio.play().catch(error => {
        console.error('音频播放失败:', error)
        this.$message.error('音频播放失败: ' + (error.message || '网络错误'))
      })
    },
    /** 获取语音类型标签 */
    getVoiceTypeLabel(type) {
      const labels = {
        'next': '即将到站',
        'arrival': '已到达',
        'departure': '发车',
        'transfer': '换乘提示',
        'terminal': '终点站',
        'safety': '安全提示',
        'custom': '自定义语音'
      }
      return labels[type] || '未知类型'
    },
    /** 获取语音类型标签颜色 */
    getVoiceTypeTagType(type) {
      const tagTypes = {
        'next': 'warning',
        'arrival': 'success',
        'departure': 'primary',
        'transfer': 'info',
        'terminal': 'danger',
        'safety': 'warning',
        'custom': 'default'
      }
      return tagTypes[type] || 'default'
    },
    /** 格式化文件大小 */
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    /** 显示统计信息 */
    showStatistics() {
      this.$router.push('/bus/files/statistics')
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const message = row ? `是否确认删除语音文件"${row.fileName}"？` : `是否确认删除选中的${this.ids.length}个语音文件？`
      this.$modal.confirm(message).then(function() {
        return delFiles(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bus/files/export', {
        ...this.queryParams
      }, `files_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
